package com.ijolas.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.ijolas.rhino.URLDecoder;

import java.awt.Image;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ListLinks {

	public static void main(String[] args) throws IOException {
		String url = "http://wallbase.cc/wallpaper/2479612";
		Document doc = Jsoup.connect(url).post();

		Elements scripts = doc.getElementsByTag("script");

		String encodedURL = null;
		String decodedURL = null;

		for (Element script : scripts) {
			if (script.html().contains("document.write") && script.html().contains("img") && script.html().contains("src")) {
				encodedURL = script.data().substring(script.data().indexOf("+B('") + 4, script.data().indexOf("')+"));
				System.out.println(encodedURL);
				decodedURL = URLDecoder.getDecodedURL(encodedURL);
				System.out.println(decodedURL);
			} // if
		} // for

		Image image = null;
		try {
			URL imageURL = new URL(decodedURL);

			InputStream is = imageURL.openStream();
			FileOutputStream fos = new FileOutputStream("/Users/kazunoriimamura/Desktop/:).jpg");

			byte[] b = new byte[2048];
			int length;

			while ((length = is.read(b)) != -1) {
				fos.write(b, 0, length);
			}

			is.close();
			fos.close();

		} // try
		catch (IOException e) {
			e.printStackTrace();
		} // catch
	}

}